/*================================================================
*   文件名称：main.cpp
*   创 建 者：yang qiang
*   创建日期：2018年09月02日
*   描    述：
*   Copyright (C) 2018 All rights reserved.
*   
================================================================*/


#include <iostream>
#include <vector>

using namespace std;

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */

class Solution {
public:
    /**
     * @param root: The root of binary tree.
     * @return: True if this Binary tree is Balanced, or false.
     */
    bool isBalanced(TreeNode * root) {
        // write your code here
        return get_depth(root) != -1;
    }

    int get_depth(TreeNode *root){
        if( !root )
            return 0;
        int leftdepth = get_depth(root->left);
        if( leftdepth == -1 )
            return -1;
        int rightdepth = get_depth(root->right);
        if( rightdepth == -1 )
            return -1;

        if( abs(leftdepth - rightdepth) > 1 )
            return -1;

        return max( leftdepth, rightdepth ) + 1;
    }
};

